package com.brave.demo;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitUtils {
    private static final long CONNECTION_TIMEOUT = 10L;
    private static final long READ_TIMEOUT = 30L;
    private static final long WRITE_TIMEOUT = 30L;
    private Retrofit retrofit;

    private static class SingletonHolder {
        private volatile static RetrofitUtils mInstance = new RetrofitUtils();
    }

    public static RetrofitUtils getInstance() {
        return SingletonHolder.mInstance;
    }

    private RetrofitUtils() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(HttpService.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
    }

    public Retrofit getRetrofit() {
        if (null == retrofit) {
            throw new RuntimeException("An empty object is referenced.");
        }
        return retrofit;
    }

    public <T> T create(final Class<T> service) {
        return getRetrofit().create(service);
    }
}